import type { ApplianceData, ApplianceDetailWithStatus } from '@/types/appliance'
import { StateTypes } from '@/constants/Appliance'
import { getAllSetting, getStatus, type ApplianceInfo, getEvents } from '@/api/appliance'
import { OPERATION_STATES, POWER_STATES } from '@/constants/Command'
import { PondingBoxStatus } from '@/constants/WDCommand'
import { getTimeStr } from '@/utils/applianceUtil'
import dayjs from 'dayjs'

/**
 * 无操作状态的家电类型
 *  - 在线/离线
 */
const NoneOperationStateAppliances = [
  // TT
  'TT',
  // HVN
  'HVN',
  // 烟机
  'Hoob',
  // 灶具
  'Hod',
  'GasHob',
  // Cookit
  'CookProcessor',
]
/**
 * 仅支持告警状态的家电类型
 *  - 在线/离线/告警
 */
// 冰箱
const ErrorStateAppliances = [
  'FridgeFreezer',
  'Freezer',
  'Refrigerator',
  // 酒柜
  'WineCooler',
  'RefrigeratorB',
  // 嵌饮机
  'BIWD',
  // 咖啡机
  'CoffeeMaker',
]
const RefrigerationAppliancesType = [
  'FridgeFreezer',
  'Freezer',
  'Refrigerator',
  // 酒柜
  'WineCooler',
]
const RefrigerationActionRequiredEvents = [
  'Refrigeration.Common.Event.ApplianceError',
  /**门长时间打开 */
  'Refrigeration.Common.Event.Door.AlarmRefrigerator',
  'Refrigeration.Common.Event.Door.AlarmFreezer',
  'Refrigeration.Common.Event.Door.AlarmWineCompartment',
  'Refrigeration.Common.Event.Door.AlarmChillerCommon',
  'Refrigeration.Common.Event.Door.AlarmFlexCompartment',
  'Refrigeration.FridgeFreezer.Event.DoorAlarmFreezer',
  'Refrigeration.FridgeFreezer.Event.DoorAlarmRefrigerator',
  /** 冰箱温度过高 */
  'Refrigeration.Common.Event.ChillerCommon.TemperatureAlarm',
  'Refrigeration.FridgeFreezer.Event.TemperatureAlarmRefrigerator',
  'Refrigeration.FridgeFreezer.Event.TemperatureAlarmFreezer',
  'Refrigeration.Common.Event.Refrigerator.TemperatureAlarm',
  'Refrigeration.Common.Event.Freezer.TemperatureAlarm',
  'Refrigeration.Common.Event.WineCompartment.TemperatureAlarm',
  /**冰箱异味难以清除 */
  'Refrigeration.Common.Event.SmartHygiene.CriticalOdor',
]
// 显示为在线的操作状态
const ShowOnlineOperationStateKeys = [
  OPERATION_STATES.PAUSE,
  OPERATION_STATES.READY,
  OPERATION_STATES.INACTIVE,
  OPERATION_STATES.STANDBY,
  OPERATION_STATES.ABORTING,
  OPERATION_STATES.FINISHED,
  OPERATION_STATES.PROGRAM_FINISHED,
]
// 显示为告警的操作状态
const ShowErrorOperationStateKeys = [
  OPERATION_STATES.ACTION_REQUIRED,
  OPERATION_STATES.ERROR,
  OPERATION_STATES.OEM_BIWD_ACTION_REQUIRED,
  OPERATION_STATES.OEM_BIWD_ERROR,
]

/**
 * 处理家电状态
 * @param item 家电数据
 * @returns 返回新的家电字段数据
 */
export async function handleStatus(item: ApplianceInfo): Promise<ApplianceDetailWithStatus> {
  const data = {
    ...item,
  } as ApplianceDetailWithStatus
  const state = data.operationState as OPERATION_STATES

  /**
   * 无操作状态判断
   */
  if (NoneOperationStateAppliances.includes(data.type)) {
    // 在线离线判断
    data.stateType = data.connected ? StateTypes.online : StateTypes.offline
    return data
  }

  /**
   * 仅支持告警状态判断
   */
  if (ErrorStateAppliances.includes(data.type)) {
    // 在线离线判断
    data.stateType = data.connected ? StateTypes.online : StateTypes.offline
    let isError = ShowErrorOperationStateKeys.includes(state)
    // 告警状态判断
    if (data.connected && RefrigerationAppliancesType.includes(data.type)) {
      const res = await getEvents(data.haId, { ignoreError: true })
      const events = res?.data?.events || []
      const hasEventError = events.some((event) => RefrigerationActionRequiredEvents.includes(event.key))
      if (hasEventError) {
        isError = true
      }
    }
    if (isError) {
      data.stateType = StateTypes.error
    }

    // BIWD判断告警
    if ((data.type === 'BIWD' && state === OPERATION_STATES.RUN) || (data.type === 'RefrigeratorB' && data.connected)) {
      const { data: biwdSettingRes } = await getAllSetting(data.haId)
      const settings = biwdSettingRes?.settings || []
      if (data.type === 'BIWD' && settings.some(({ key, value }) => key === PondingBoxStatus && value === 1)) {
        data.stateType = StateTypes.error
      }
      if (
        data.type === 'RefrigeratorB' &&
        settings.some(
          ({ key, value }) => key === 'Refrigeration.RefrigeratorB.Status.ErrorList' && (value === 1 || value === 2)
        )
      ) {
        data.stateType = StateTypes.error
      }
    }

    return data
  }

  /**
   * 支持预约、运行中状态的显示状态判断
   */
  // 离线状态
  if (!data.connected) {
    data.stateType = StateTypes.offline
    return data
  }
  // 无操作状态
  if (!data.operationState) {
    data.stateType = StateTypes.online
    return data
  }
  // 显示在线
  if (ShowOnlineOperationStateKeys.includes(state)) {
    data.stateType = StateTypes.online
    return data
  }
  // 显示告警
  if (ShowErrorOperationStateKeys.includes(state)) {
    data.stateType = StateTypes.error
    return data
  }

  switch (state) {
    // 运行中
    case OPERATION_STATES.RUN: {
      data.stateType = StateTypes.running
      /**
       * 预计结束时间格式化
       */
      const finishTime = data.displayTimes?.finishInAbsolute || null
      data.timeDuration = finishTime === null ? '' : getTimeStr(finishTime)
      return data
    }
    // 已预约
    case OPERATION_STATES.DELAYED_START:
    case OPERATION_STATES.OEM_OVEN_DELAYED_START: {
      data.stateType = StateTypes.reserved
      /**
       * 预计结束时间格式化
       */
      // OEM烤箱、蒸箱 特殊处理
      if (['OvenB', 'SteamerB'].includes(data.type)) {
        const finishTime = data.displayTimes?.finishInAbsolute || null
        const remainingProgramTime = data.displayTimes?.remainingProgramTime || null
        // 无预约时间
        if (!finishTime || !remainingProgramTime) {
          data.timeDuration = ''
          return data
        }

        // 时间格式化
        const finishDate = new Date(finishTime.replace(/-/g, '/'))
        const startDate = new Date(finishDate.getTime() - remainingProgramTime * 1000)
        const startTimeStr = dayjs(startDate).format('HH:mm')
        const finishTimeStr = dayjs(finishDate).format('HH:mm')
        data.timeDuration = `${startTimeStr}-${finishTimeStr}`
        return data
      }

      // 其他家电
      const startTime = data.displayTimes?.startInAbsolute || null
      const finishTime = data.displayTimes?.finishInAbsolute || null
      // 无预约时间
      if (startTime === null || finishTime === null) {
        data.timeDuration = ''
        return data
      }

      // 时间格式化
      const startTimeStr = getTimeStr(startTime)
      const finishTimeStr = getTimeStr(finishTime)
      data.timeDuration = ` ${startTimeStr}-${finishTimeStr}`
      return data
    }
    default: {
      // 在线离线判断
      data.stateType = data.connected ? StateTypes.online : StateTypes.offline
      return data
    }
  }
}
